#!/bin/bash

#    / **  
#    * 文件名：安装vim 从github源码安装
#    * 版权： Copyright 谢振斌  All Rights Reserved.  
#    * 修改内容：新增  
#    * 修改人： 谢振斌  
#    * 修改时间：2021-3-23  
#    */  


#    / **  
#    *〈 判断shell系统类型 〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [参数1说明]  
#    * @param [参数2] [参数2说明]  
#    * @return [返回类型说明]  String [linux、osx、bsd] 
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function getShellOStype()
{
    SHELL_PLATFORM='unknown';
    ## echo "[Debug] SHELL_PLATFORM=${SHELL_PLATFORM}"

    ## echo $OSTYPE | tr '[A-Z]' '[a-z]'"
    shellostypestring=`echo $OSTYPE`;
    ## echo "[Debug] shellostypestring=${shellostypestring}"

    ## 从字符串中识别shell系统类型
    case "${shellostypestring}" in
        *'linux'*   ) SHELL_PLATFORM='linux'    ;;
        *'darwin'*  ) SHELL_PLATFORM='osx'      ;;
        *'bsd'*     ) SHELL_PLATFORM='bsd'      ;;
    esac

    # if [[ $SHELL_PLATFORM == 'linux' || $SHELL_PLATFORM == 'bsd' ]]; then
    #    echo "[Debug] linux"
    # elif [[ $SHELL_PLATFORM == 'osx' ]]; then
    #    # $SHELL_PLATFORM == 'bsd'
    #    echo "[Debug] osx Shell"
    # elif [[ $SHELL_PLATFORM == 'bsd' || $SHELL_PLATFORM == 'osx'  ]]; then
    #    echo "[Debug] bad shell"
    # else
    #    echo "[Debug] unknown"
    # fi

    # 返回值
    echo $SHELL_PLATFORM;
}


#    / **  
#    *〈获得linux发行版本名称〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [参数1说明]  
#    * @param [参数2] [参数2说明]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function getDistName()
{
    if grep -Eqii "Arch Linux" /etc/issue || grep -Eq "Arch Linux" /etc/*-release; then
        DISTRO='Arch Linux'
        PM='pacman'
    elif grep -Eqii "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
        DISTRO='CentOS'
        PM='yum'
    elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then
        DISTRO='RHEL'
        PM='yum'
    elif grep -Eqi "Aliyun" /etc/issue || grep -Eq "Aliyun" /etc/*-release; then
        DISTRO='Aliyun'
        PM='yum'
    elif grep -Eqi "Fedora" /etc/issue || grep -Eq "Fedora" /etc/*-release; then
        DISTRO='Fedora'
        PM='yum'
    elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
        DISTRO='Debian'
        PM='apt'
    elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
        DISTRO='Ubuntu'
        PM='apt'
    elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then
        DISTRO='Raspbian'
        PM='apt'
    else
        DISTRO='unknow'
    fi

    # 返回值
    echo $DISTRO;
}

#    / **  
#    *〈 安装软件 〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [软件名称]  
#    * @param [参数2] [用来判断是否已经安装的软件名称，可为空，为空则，与参数1来判断是否存在]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function installSoftware()
{
    echo "[INFO] 安装软件";
    softwareName=$1;
    echo "[Debug] softwareName="${softwareName};
    # 判断是否已经安装
    #cmdStr="which ${softwareName}"
    #echo "[Debug] cmdStr="${cmdStr}
    #if [ ! -x "$( which ${softwareName} )" ]; then
    #    echo "[Debug] 未安装软="${softwareName}
    #else
    #    echo "[Debug] 已经安装软="${softwareName}
    #fi
    #exit
    softwareName2=$2;
    if [  ! $softwareName2 ];then
        echo "[INFO] 软件安装与用来判断是否安装的名称相同"
        softwareName2=${softwareName};
        echo "[Debug] softwareName2="${softwareName2};
    else
        echo "[INFO] 软件安装名称与用来判断是否安装的名称不同！";
        #softwareName2=$2;
        echo "[Debug] softwareName2="${softwareName2};
    fi
    echo "[INFO] 判断系统中是否已经存在"${softwareName2};
    if [ ! -x "$( which ${softwareName2} )" ]; then
        echo "[INFO] 软件${softwareName}未安装！"
        # 获取当前shell系统（判断是mac、还是linux）
        shellSystemType=$(getShellOStype)
        echo "[Debug] shellSystemType="${shellSystemType}
        if [ "$shellSystemType" == "linux" ]; then
            # 获取当前系统发行版本
            linuxSystemDistType=$(getDistName)
            echo "[Debug] linuxSystemDistType="${linuxSystemDistType}
            # 命令拼接
            #cmdStr="ln -s  "${dir}"/zshrc-oh-my-sh  "${HOME}"/.zshrc"
            #cmdStr="git clone "${URL}${pluginsName}" "${pluginsPath}
            #echo "执行命令: ${cmdStr}"
            #${cmdStr}
            if [ "$linuxSystemDistType" == "CentOS" ]; then
                echo "[Debug] ======= CentOS"
                # 执行另一个脚本
                # /bin/bash ./zsh1.sh  
                #cmdStr="ln -s  "${dir}"/zshrc-oh-my-sh  "${HOME}"/.zshrc"
                cmdStr="yum install "${softwareName}
                echo "执行命令: ${cmdStr}"
                ${cmdStr}
            elif [ "$linuxSystemDistType" == "Arch Linux" ] ; then
                echo "[Debug] ======= Arch Linux"
                cmdStr="yay -S "${softwareName}
                echo "执行命令: ${cmdStr}"
                ${cmdStr}
            else
                echo "[Debug] ======= unknow linux dist"
                echo "[INFO] 不知道当前linux系统是什么发行版本，不知到该用什么包管理软件进行安装！软件${systemType}！"
            fi
      elif [ "$shellSystemType" == "osx" ]; then
           echo "[Debug] ======= shellSystemType是darwin，所以是 osx（macOS）"
           # 权限设置，解决部分软件无法安装问题：如 lua
           cmdStr="sudo chown -R $(whoami) /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig"
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
           cmdStr="chmod u+w /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig"
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
           # 使用软件包管理器安装软件
           cmdStr="brew install "${softwareName}
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
      else
        echo "[Debug] ======= unknow shell system type"
        echo "[INFO] 不知道当前系统是 linux bsd osx（macOS）！不知道该用什么包管理器安装软件${systemType}！"
      fi 
      if [ ! $? -eq 0 ]; then
        echo ""
        echo "[ERROR]: 安装软件${softwareName}  失败 !!！ 退出"
        exit
      fi
    else
        echo "[INFO] 软件${softwareName}已经存在！"
    fi
}

#    / **  
#    *〈 判断文件夹是否存在，不存在则，建立链接，存在则备份并建立链接 〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [文件路径]  
#    * @param [参数2] [链接建立命令]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function bakAndLinkFolder()
{

    echo "[Debug]: bakAndLinkFolder !";
    # folderPath=${HOME}"/.vim"
    folderPath=$1;
    echo "[INFO]: bakAndLinkFolder=${folderPath}";
    commandStr=$2;
    echo "[INFO]: commandStr=${commandStr}";
    # 判断是文件夹是否已经存在
    if [ ! -d "$folderPath" ]; then
        echo "[INFO]: ${folderPath} 不存在!";
    else
        echo "[INFO]: ${folderPath} 已经存在!";
        # 备份文件
        echo "[INFO] 备份文件夹 ${folderPath}";
        cmdStr="mv ${folderPath} ${folderPath}-`date +%y%m%d%H%M%S`";
        echo "执行命令: ${cmdStr}";
        ${cmdStr}
    fi
    # 命令拼接
    #echo "[INFO]: 创建文件夹软链接";
    #commandStr="ln -s  "${dir}"/vimrc  "${HOME}"/.vimrc"
    echo "执行命令: ${commandStr}";
    ${commandStr}
}

#    / **  
#    *〈 判断文件是否存在，不存在则执行命令，存在则备份后执行命令 〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [文件路径]  
#    * @param [参数2] [要执行的命令]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    * 注：参数中带有空格，如果直接写的话，会从空格处自动切分开。解决方法：将这个引用变量用双引号括起来
#    */  
function bakAndLinkFile()
{

    # configFilePath=${HOME}"/.vimrc"
    configFilePath=$1;
    commandStr=$2;
    # 判断是文件是否已经存在
    if [ ! -f "$configFilePath" ]; then
        echo "[INFO]: ${configFilePath} 不存在!";
    else
        echo "[INFO]: ${configFilePath} 已经存在!";
        # 备份文件
        echo "[INFO] 备份文件 ${configFilePath}";
        cmdStr="mv ${configFilePath} ${configFilePath}-`date +%y%m%d%H%M%S`";
        echo "执行命令: ${cmdStr}";
        ${cmdStr}
    fi
    # 命令拼接
    #echo "[INFO]: 创建文件软链接";
    #commandStr="ln -s  "${dir}"/vimrc  "${HOME}"/.vimrc"
    echo "执行命令: ${commandStr}";
    ${commandStr}
}

#    / **  
#    *〈流程控制〉  
#    *〈该脚本的主函数〉  
#    * @param [无]  
#    * @return [无]  
#    * @exception/throws [无]  
#    * @deprecated  
#    */  
function processControlMain()  
{  
    # 打印当前系统时间  
    echo "Start..."  
    date  

    # 此处是你的代码  
    # ...  
    # fun1
	# 获取当前脚本目录位置
	cd `dirname $0`
	dir=`pwd`
	echo ${dir}

    # 依赖
    installSoftware "git"
    installSoftware "bat"

    installSoftware "lua"
    
    installSoftware "ruby"
    installSoftware "rbenv"
    installSoftware "ruby-build"

    installSoftware "python"

    installSoftware "fzf"
    installSoftware "rgpgrep" "rg"
    installSoftware "ack"
    installSoftware "ranger"
    installSoftware "tig"
    installSoftware "lazygit"

    installSoftware "nodejs" "node"
    installSoftware "npm"
    installSoftware "yarn"
    # installSoftware "lazynpm"
      
    # pip3 install --user --upgrade pynvim

    # 下载vim源码
    if [ -d "./vim"  ] ;then
        echo "[Debug] vim目录不存在！"
        # git clone https://github.com/vim/vim.git
        # git clone https://hub.fastgit.org/vim/vim.git
        git clone https://ghproxy.com/https://github.com/vim/vim.git

        # 切换进目录
        cd vim/src
    elif [ -h "./vim" ] ; then
        echo "[Debug] vim目录不存在！（软/硬链接）"
        # git clone https://github.com/vim/vim.git
        # git clone https://hub.fastgit.org/vim/vim.git
        git clone https://ghproxy.com/https://github.com/vim/vim.git
        # 切换进目录
        cd vim/src
    else
        echo "[Debug] vim目录存在！"
        # 切换进目录
        cd vim
        # 更新
        # git pull
        # 切换目录
        cd src
    fi
    
    # 解决Mojave 'ruby/config.h' file not found
    # cd  /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0/ruby 
    # sudo ln -s ../universal-darwin20/ruby/config.h ./config.h

    # 删除原来vim
    sudo rm -rf /usr/local/bin/vim
    sudo rm -f /usr/bin/vim
    # 清除旧配置缓存
    sudo rm -f auto/config.cache
    # 进行编译
    make clean


    # 获取当前shell系统（判断是mac、还是linux）
    shellSystemType=$(getShellOStype)
    echo "[Debug] shellSystemType="${shellSystemType}
    if [ "$shellSystemType" == "linux" ]; then
        echo "[Debug] 这是 linux "
        cmdStr="./configure --prefix=/usr/local/bin/vim
                    --with-features=huge \
                    --enable-rubyinterp=yes \
                    --enable-pythoninterp=yes \
                    --with-python-command=/usr/bin/python2 \
                    --enable-python3interp=yes \
                    --with-python3-command=/usr/bin/python3 \
                    --enable-perlinterp=yes \
                    --enable-multibyte \
                    --enable-luainterp=yes \
                    --enable-gui=gtk2 \
                    --enable-cscope ";
    elif [ "$shellSystemType" == "osx" ]; then
        echo "[Debug] 这是 MacOS "
        cmdStr="./configure --prefix=/usr/local/bin/vim
                    --with-features=huge \
                    --enable-rubyinterp=yes \
                    --with-ruby-command=/usr/bin/ruby \
                    --enable-pythoninterp=yes \
                    --with-python-command=/usr/bin/python2 \
                    --enable-python3interp=yes \
                    --with-python3-command=/Library/Frameworks/Python.framework/Versions/3.9/bin/python3 \
                    --enable-perlinterp=yes \
                    --enable-multibyte \
                    --enable-luainterp=yes \
                    --with-lua-prefix=/usr/bin/lua \
                    --enable-gui=gtk2 \
                    --enable-cscope ";
    else
        echo "[Debug] 未知系统";
        exit;
    fi
    echo "执行命令: ${cmdStr}";

    ${cmdStr}
    #sudo make install

    sudo make && sudo make install

    # 备注说明:
        # --with-features=huge                         ：支持最大特性
        # --enable-rubyinterp                          ：打开对ruby编写的插件的支持
        # --enable-pythoninterp                        ：打开对python编写的插件的支持
        # --enable-python3interp                       ：打开对python3编写的插件的支持
        # --with-python-config-dir=/usr/bin/python2   : 指定 python2 路径
        # --with-python-config-dir=/usr/bin/python3   : 指定python3 路径
        # --enable-luainterp                            ：打开对lua编写的插件的支持
        # --enable-perlinterp                           ：打开对perl编写的插件的支持
        # --enable-multibyte                            ：打开多字节支持，可以在Vim中输入中文

        # --enable-rubyinterp                           ：启用Vim对ruby的支持  
        # --enable-pythoninterp                         ：启用Vim对python的支持  
        # --enable-luainterp                             ：启用Vim对lua的支持  
        # --with-lua-prefix=/usr/bin/lua                :指定lua的安装路径,默认为 $LUA_PREFIX  

        # --enable-sniff                                 ：Vim状态提示 提示Vim当前处于INSERT、NORMAL、VISUAL哪种模式  
        # --enable-cscope                                ：Vim对cscope支持  
        # --disable-gui                                  ：不用编译生成图形界面版gvim  
        # --prefix=/opt/local/vim                       ：编译安装路径 

    cmdStr="sudo cp  /usr/local/bin/vim /usr/bin/"
    echo "执行命令: ${cmdStr}";
    ${cmdStr}
   

    echo "查看是否有 支持某特性, 如： python，python3，lua，方法如下："
    echo "例：查看是否支持 Python"
    echo "执行命令: vim --version | grep python"
    echo "查看是否有 +Python, 如果python，python3前有减号，说明不支持"
    echo "或者，在vim中输入:version 可以看是否有到+python的信息，即有表示支持Python了."
    echo '或者，在vim中输入:echo has（"python"）返回1，则支持python；'
    echo '或者，在vim中输入:echo has（"python3"）返回1，则支持python3；'

    # echo "/usr/local/bin/vim --version | grep python"
    cmdStr="./vim --version | grep python"
    echo "执行命令: ${cmdStr}";
    ${cmdStr}

    echo "vim --version | grep python"
    cmdStr="vim --version | grep python"
    echo "执行命令: ${cmdStr}";
    ${cmdStr}

    echo "vim --version | grep lua"
    cmdStr="vim --version | grep lua"
    echo "执行命令: ${cmdStr}";
    ${cmdStr}

    # 打印当前系统时间  
    date;
    echo "The End."

} 

# 执行入口
# 进入脚本目录位置
cd `dirname $0`
# 获取当前脚本目录位置
shellfilepath=`pwd`'/'$0
# 打印脚本目录地址
echo "[INFO]: 脚本地址 "${shellfilepath}

if true  
# if false  
then  
    echo "[Debug] true"
    # 开始执行  从标准输入中读取并同时写入到标准输出和指定的文件上 
    ## 拼接日志文件地址
    #logfilepath=`pwd`'/'$0'.log'
    logfilepath=`pwd`'/'$0'-'$(date +%Y%m%d)'.log'
    #logfilepath=`pwd`'/'$0'-'$(date +%Y%m%d-%H-%M-%S)'.log'
    ## 打印日志文件地址
    echo "[INFO]: 日志地址" ${logfilepath}
    processControlMain  | tee -a ${logfilepath}
else  
    echo "[Debug] false"  
    ## 函数单元测试  
    #  
fi

# 脚本结束  
# 软件配置文件软链接设置脚本



